﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.TradeChannel.Gyb.Response
{
    /// <summary>
    /// 付款通知响应
    /// </summary>
    [Serializable]
    abstract class NotifyResponse<TEntity> : AResponse where TEntity : NotifyResponseEntity
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        protected NotifyResponse(IDictionary<string, string> message)
        {
            string _transName, _Plain, _Signature, _ErrorCode, _ErrorMsg;
            message.TryGetValue("transName", out _transName);
            message.TryGetValue("Plain", out _Plain);
            message.TryGetValue("Signature", out _Signature);
            message.TryGetValue("ErrorCode", out _ErrorCode);
            message.TryGetValue("ErrorMsg", out _ErrorMsg);
            transName = _transName;
            Plain = _Plain;
            Signature = _Signature;
            ErrorCode = _ErrorCode;
            ErrorMsg = _ErrorMsg;
        }

        /// <summary>
        /// 交易名称
        /// </summary>
        public string transName { get; private set; }

        /// <summary>
        /// 交易内容信息
        /// </summary>
        public string Plain { get; private set; }

        /// <summary>
        /// 网关签名
        /// </summary>
        public string Signature { get; private set; }

        /// <summary>
        /// 错误码
        /// </summary>
        public string ErrorCode { get; private set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string ErrorMsg { get; private set; }

        /// <summary>
        /// 是否交易正常
        /// </summary>
        public bool IsSuccess()
        {
            return !string.IsNullOrWhiteSpace(this.Plain) && !string.IsNullOrWhiteSpace(this.Signature);
        }

        /// <summary>
        /// 签名检查
        /// </summary>
        /// <param name="channel">通道</param>
        /// <param name="config">配置</param>
        /// <returns></returns>
        public bool SignVeryfy(ITradeChannel channel, GybConfigure config)
        {
            if (string.IsNullOrWhiteSpace(Plain))
            {
                return false;
            }
            if (string.IsNullOrWhiteSpace(Signature))
            {
                return false;
            }
            return SecurityUtils.SignVerify(config.ConfigureInfo, Signature, Plain);
        }

        /// <summary>
        /// 转为实体
        /// </summary>
        /// <returns></returns>
        public TEntity ToEntity()
        {
            return ToEntity(AnalyzePlain(Plain));
        }

        /// <summary>
        /// 转为实体
        /// </summary>
        /// <returns></returns>
        protected abstract TEntity ToEntity(IDictionary<string, string> plainDic);
    }
}
